package com.yc.sakuralxm.uestcscanning

import android.Manifest
import android.app.AlertDialog
import android.app.Service
import android.content.ComponentName
import android.content.DialogInterface
import android.content.Intent
import android.content.ServiceConnection
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.view.KeyEvent
import android.view.View
import android.widget.Toast

import com.kernal.plateid.AuthService
import com.kernal.plateid.PlateAuthParameter
import com.kernal.plateid.RecogService
import com.yc.sakuralxm.uestcscanning.ocrscan.Devcode
import com.yc.sakuralxm.uestcscanning.ocrscan.MemoryCameraActivity
import com.yc.sakuralxm.uestcscanning.ocrscan.PermissionActivity
import com.yc.sakuralxm.uestcscanning.tools.FilePathUtil
import com.yc.sakuralxm.uestcscanning.tools.IntentUtil
import com.yc.sakuralxm.uestcscanning.tools.L
import com.yc.sakuralxm.uestcscanning.tools.SharedPreferencesUtils
import com.yc.sakuralxm.uestcscanning.zxing.CaptureActivity

import java.io.File

import utills.CheckPermission

class MainActivity : BaseActivity() {
    private var sn = ""

    private var isTouch = false
    private var index = 0

    var authBinder: AuthService.MyBinder? = null  // 权限认证;

    var authConn: ServiceConnection = object : ServiceConnection {

        private var ReturnAuthority = -1
        override fun onServiceDisconnected(name: ComponentName) {
            authBinder = null
        }

        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            authBinder = service as AuthService.MyBinder
            Toast.makeText(applicationContext, com.kernal.plateid.R.string.auth_check_service_bind_success, Toast.LENGTH_SHORT).show()
            try {
                val pap = PlateAuthParameter()
                pap.sn = sn
                pap.authFile = ""
                pap.devCode = Devcode.DEVCODE
                ReturnAuthority = authBinder!!.getAuth(pap)
                if (ReturnAuthority != 0) {
                    Toast.makeText(applicationContext, getString(com.kernal.plateid.R.string.license_verification_failed) + ":" + ReturnAuthority, Toast.LENGTH_LONG).show()
                } else {
                    //                    Toast.makeText(getApplicationContext(), com.kernal.plateid.R.string.license_verification_success+11, Toast.LENGTH_LONG).show();


                    SharedPreferencesUtils.writeTure(applicationContext, true)
                    //                    SharedPreferencesUtils.writeAccessToken(getApplicationContext(), SharedPreferencesUtils.KEY_UID);
                    val dir = File(FilePathUtil.sdCardPath)
                    L.e(FilePathUtil.sdCardPath)
                    if (!dir.exists())
                        dir.mkdirs()
                    FilePathUtil.stringTxt(SharedPreferencesUtils.KEY_UID)
                }
            } catch (e: Exception) {
                Toast.makeText(applicationContext, com.kernal.plateid.R.string.failed_check_failure, Toast.LENGTH_SHORT).show()
                e.printStackTrace()
                L.e(e.toString())
            } finally {
                if (authBinder != null) {
                    unbindService(this)
                }
            }
        }

        // sn：采用序列号方式激活时设置此参数，否则写""
        // authfile：采用激活文件方式激活时设置此参数，否则写""
        // 以上俩个参数都不为""时按序列号方式激活；当sn和authfile为""时会在根目录下找激活文件xxxxxxxxxxxxxxx_cp.txt
        //            	pap.server =  "http://192.168.0.36:8080";
        //            	authfile=PATH+"/AndroidWT/auth/authfile.db";//文件激活方式路径


        //            	pap.dataFile = datefile;
        //            	pap.dataFile = PATH+"/AndroidWT/dataauth/wtdate.lsc";

        //            	pap.versionfile = PATH+"/AndroidWT/wtversion.lsc";

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val authIntent = Intent(activity, AuthService::class.java)
        sn = SharedPreferencesUtils.KEY_UID

        bindService(authIntent, authConn, Service.BIND_AUTO_CREATE)
        L.e("执行到了这里授权")
        //        }
        setContentView(R.layout.activity_main)
        title = "电子科大车辆管控移动端"

        findViewById(R.id.idImgB).visibility = View.INVISIBLE
    }

    fun go(view: View) {
        IntentUtil.startActivity(activity, com.yc.sakuralxm.uestcscanning.ocrscan.MainActivity::class.java)

    }

    fun goCar(view: View) {

        //        CreatDialog();

        isTouch = false
        var video_intent = Intent()
        video_intent.putExtra("camera", true)
        RecogService.recogModel = true//true  精准模式
        video_intent = Intent(activity, MemoryCameraActivity::class.java)
        if (Build.VERSION.SDK_INT >= 23) {
            val checkPermission = CheckPermission(activity)
            if (checkPermission.permissionSet(*PERMISSION)) {
                PermissionActivity.startActivityForResult(activity, 0, "true", *PERMISSION)

            } else {
                video_intent.setClass(applicationContext, MemoryCameraActivity::class.java)
                video_intent.putExtra("camera", true)
                startActivity(video_intent)
                //                        finish();
            }
        } else {
            video_intent.setClass(applicationContext, MemoryCameraActivity::class.java)
            video_intent.putExtra("camera", true)
            startActivity(video_intent)
            //                    finish();
        }
        //            	video_intent.setClass(getApplicationContext(),  MemoryCameraActivity.class);
        //            	startActivity(video_intent);dialog.dismiss();

    }

    //    }
    //    @Override
    //    public void onAttachedToWindow()
    //    {
    //        this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
    //        super.onAttachedToWindow();
    //    }

    //    @Override
    //    public void onAttachedToWindow()
    //    {
    //        //分析setType参数为TYPE_KEYGUARD的原因，见(a)
    //        this.getWindow().setType(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
    //        super.onAttachedToWindow();
    //    }
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {


        if (keyCode == KeyEvent.KEYCODE_BACK) {
            AppContext.app.showToastCenterLong("如果您确实需要退出请联系开发商")
            return false
        }
        if (keyCode == KeyEvent.KEYCODE_MOVE_HOME) {
            AppContext.app.showToastCenterLong("如果您确实需要退出请联系开发商")
            return false
        }
        if (keyCode == KeyEvent.KEYCODE_HOME) {
            AppContext.app.showToastCenterLong("如果您确实需要退出请联系开发商")
            return true
        }
        //        AppContext.getApp().showToastCenterShort("竟然执行到了这里");
        return false
    }

    private fun CreatDialog() {
        // TODO Auto-generated method stub
        val builder = AlertDialog.Builder(activity)
        //        builder.setIcon(R.drawable.ic_launcher);
        builder.setTitle("请选择识别模式")
        val model = arrayOf("精准模式", "快速模式")

        //    设置一个单项选择下拉框
        /**
         * 第一个参数指定我们要显示的一组下拉单选框的数据集合
         * 第二个参数代表索引，指定默认哪一个单选框被勾选上，0表示默认'精准模式' 会被勾选上   1 表示快速模式
         * 第三个参数给每一个单选项绑定一个监听器
         */
        builder.setSingleChoiceItems(model, index) { dialog, which ->
            index = which
            isTouch = true
        }
        builder.setPositiveButton("确定") { dialog, which ->
            isTouch = false
            var video_intent = Intent()
            video_intent.putExtra("camera", true)
            RecogService.recogModel = index != 1
            video_intent = Intent(activity, MemoryCameraActivity::class.java)
            if (Build.VERSION.SDK_INT >= 23) {
                val checkPermission = CheckPermission(activity)
                if (checkPermission.permissionSet(*PERMISSION)) {
                    PermissionActivity.startActivityForResult(activity, 0, "true", *PERMISSION)

                } else {
                    video_intent.setClass(applicationContext, MemoryCameraActivity::class.java)
                    video_intent.putExtra("camera", true)
                    startActivity(video_intent)
                    //                        finish();
                }
            } else {
                video_intent.setClass(applicationContext, MemoryCameraActivity::class.java)
                video_intent.putExtra("camera", true)
                startActivity(video_intent)
                //                    finish();
            }
            //            	video_intent.setClass(getApplicationContext(),  MemoryCameraActivity.class);
            //            	startActivity(video_intent);dialog.dismiss();
        }
        builder.setNegativeButton("取消") { dialog, which ->
            if (isTouch) {
                if (index == 0) {
                    index = 1
                } else {
                    index = 0
                }
                isTouch = false
            }
            dialog.dismiss()
        }
        builder.show()
    }

    fun goLive(view: View) {
        IntentUtil.startActivity(activity, CaptureActivity::class.java)
    }

    companion object {

        internal val PERMISSION = arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, // 写入权限
                Manifest.permission.READ_EXTERNAL_STORAGE, // 读取权限
                Manifest.permission.READ_PHONE_STATE, Manifest.permission.VIBRATE, Manifest.permission.INTERNET)
    }

}
